<template>
  <div>
    <el-button type="primary" @click="handelsearch">拉框搜索</el-button>
    <div class="search-table" v-show="tableData.length > 0">
      <el-table :data="tableData" style="width: 100%" @row-click="handleRowClick">
        <el-table-column prop="event_num" label="事故编号"></el-table-column>
        <el-table-column prop="level" label="事故级别"></el-table-column>
        <el-table-column prop="area" label="事故区域"></el-table-column>
        <el-table-column prop="name" label="事故类型"></el-table-column>
        <el-table-column prop="car_num" label="车牌号码"></el-table-column>
        <el-table-column prop="phone" label="联系方式"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { inject, onMounted, ref, onUnmounted } from 'vue'
import { DrawEvent, DrawRect } from '@antv/l7-draw'
import { getWuhanEvent } from '@/assets/api/index'
import { PointLayer } from '@antv/l7'
import * as turf from '@turf/turf'
const mapScene = inject('mapScene')
const tableData = ref([])
const totalData = ref([])
let draw
let pointlayer
onMounted(async () => {
  mapScene.value.map.flyTo({
    center: [114.29, 30.59],
    zoom: 10,
    pitch: 45,
  })
  const { data } = await getWuhanEvent()
  totalData.value = data
})

function handelsearch() {
  if (draw) {
    draw.clear()
    draw.destroy()
    draw = null
  }
  if (pointlayer) {
    mapScene.value.scene.removeLayer(pointlayer)
    pointlayer = null
  }
  draw = new DrawRect(mapScene.value.scene, {})
  draw.enable()
  draw.on(DrawEvent.Add, (e) => {
    let result = turf.pointsWithinPolygon(totalData.value, e)
    pointlayer = new PointLayer({
      name: '事故点',
    })
    pointlayer.source(result).shape('circle').size(30).color('#f00').active(true).animate(true)
    mapScene.value.scene.addLayer(pointlayer)
    tableData.value = result.features.map((item) => ({
      ...item.properties,
      center: item.geometry.coordinates,
    }))
  })
}
function handleRowClick(row) {
  tableData.value = []
  if(draw){
    draw.clear()
    draw.destroy()
    draw = null
  }
  let center = row.center
  mapScene.value.map.flyTo({
    center: center,
    zoom: 15,
    pitch: 0,
  })
}

onUnmounted(() => {
  if (draw) {
    draw.clear()
    draw.destroy()
    draw = null
  }
  if (pointlayer) {
    mapScene.value.scene.removeLayer(pointlayer)
    pointlayer = null
  }
})
</script>

<style scoped>
.el-button {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 9999;
}
.search-table {
  position: fixed;
  width: 60%;
  bottom: 100px;
  left: 20%;
  z-index: 9999;
}
.search-table .el-table {
  max-height: 200px;
  overflow: auto;
}
:deep(.el-table__cell){
  background-color: aliceblue;
}
</style>
